import {
    memo,
    useEffect,
    useRef,
    useState,
    useMemo
} from 'react'
import { debounce } from '@/utils'
import {
    ArrowLeft,
    DeleteO
} from '@react-vant/icons'
import styles from './search.module.css'

const SearchBox = (props) => {
    // /api
    // 单向数据流
    // 子父通信
    const [query, setQuery] = useState('')
    const { handleQuery } = props
    // 非受控组件
    const queryRef = useRef(null)
    const handleChange = (e) => {
        let val = e.currentTarget.value
        setQuery(val)
    }
    const clearQuery = () => {
        setQuery('')
        queryRef.current.value = ''
        queryRef.current.focus()
    }
    // 防抖
    // useMemo 缓存debounce结果 否则会反复执行
    const handleQueryDebounce = useMemo(() => {
        return debounce(handleQuery, 500)
    }, [])
    const displayStyle = {
        fontSize: '20px',
        display: query ? 'block' : 'none'
    }
    useEffect(() => {
        handleQueryDebounce(query)
    }, [query])
    return (
        <div className={styles.wrapper}>
            <ArrowLeft
            style={{
                fontSize: '20px'
            }}
             onClick={() => {
                history.go(-1)
            }} />
            <input
                type="text"
                className={styles.ipt}
                placeholder="搜索音乐相关"
                ref={queryRef}
                onChange={
                    handleChange
                }
            />
            {/* 移动端用户体验 */}
            <DeleteO onClick={clearQuery} style={displayStyle} />
        </div>
    )
}

export default memo(SearchBox)